from flask import Blueprint, render_template, g, request, flash, redirect, url_for
from utils import login_required
from .forms import QuestionForm, AnswerForm
from models import QuestionModel, UserModel, AnswerModel
from exts import db
from sqlalchemy import or_


bp = Blueprint(name='qa', import_name=__name__, url_prefix='/')

@bp.route('/')
def index():
    questions = QuestionModel.query.all()
    # ??? SQL排序
    return render_template('index.html', questions=questions)
    

# 判断登陆,如果未登陆返回login
@bp.route('/question/public', methods=['GET', 'POST'])
@login_required
def public_question():
    if request.method == 'POST':
        form = QuestionForm(formdata=request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(
                title=title,
                content=content,
                author=g.user
            )
            db.session.add(question)
            db.session.commit()
            return redirect('/')
        else:
            flash('标题或内容格式错误!')
            return redirect(url_for('qa.public_question'))
    else:
        return render_template('public_question.html')


@bp.route('/question/<int:question_id>')
def question_detail(question_id):
    question = QuestionModel.query.get(question_id)
    return render_template('detail.html', question=question)


@bp.route('/answer/<int:question_id>', methods=['POST'])
@login_required
def answer(question_id):
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data
        # question_id = form.question_id.data
        answer_model = AnswerModel(content=content, question_id=question_id, author=g.user)
        db.session.add(answer_model)
        db.session.commit()
        flash('评论成功!')
    else:
        flash('评论失败!')
    return redirect(url_for('qa.question_detail', question_id=question_id))


@bp.route('/search')
def search():
    # http://qa/search?search_query=xxx
    q = request.args.get('search_query')
    questions = QuestionModel.query.filter(or_(QuestionModel.title.contains(q), QuestionModel.content.contains(q)))
    return render_template('index.html', questions=questions)